package com.zzsy.carosshopprojects.activitys.home.mainpage.common;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;

import com.king.base.util.ToastUtils;
import com.sunmi.pay.hardware.aidlv2.AidlConstantsV2;
import com.sunmi.pay.hardware.aidlv2.readcard.CheckCardCallbackV2;
import com.sunmi.pay.usdk.aidl.AidlConstants;
import com.sunmi.pay.usdk.aidl.bean.CardInfo;
import com.sunmi.pay.usdk.aidl.readcard.ReadCardCallback;
import com.zzsy.carosshopprojects.P2_verson_data.CheckCardCallbackV2Wrapper;
import com.zzsy.carosshopprojects.R;
import com.zzsy.carosshopprojects.base.BaseViewMode;
import com.zzsy.carosshopprojects.util.ApkInfoUtil;
import com.zzsy.carosshopprojects.util.StringUtils;
import com.zzsy.carosshopprojects.util.sunmireadcard.SunmiReadCardHelper;

import androidx.annotation.NonNull;
import androidx.fragment.app.DialogFragment;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.MutableLiveData;

/**
 * 公共的读卡Mode
 */
public class ReadCardMode extends BaseViewMode {

    private int cardType;
    private Activity activity;
    private DialogFragment dialogFragment;

    private MutableLiveData<String> liveData;


    public MutableLiveData<String> getLiveData() {
        if (liveData == null)
            liveData = new MutableLiveData<>();
        return liveData;
    }

    /**
     * 验卡
     */
    public void checkCards(Object object) {
        if (object instanceof Activity) {
            this.activity = (Activity) object;
        } else if (object instanceof DialogFragment) {
            this.dialogFragment = (DialogFragment) object;
        }

        String versionData = ApkInfoUtil.getVersionData();
        if (!StringUtils.isEmpty(versionData)) {
            if ("P1_4G".equals(versionData)) {
                shuaCard();
            } else {
                checkCard();
            }
        } else {
            showContent(R.string.CheckCardService);
            close();
        }
    }

    /**
     * P1-4G刷卡
     */
    private void shuaCard() {
        cardType = AidlConstants.CardType.MIFARE.getValue();
        try {
            SunmiReadCardHelper.getInstance().getReadCardOpt().checkCard(cardType, readCardCallback, 60);
        } catch (RemoteException e) {
            e.printStackTrace();
            showContent(R.string.checkCardError);
            close();
        }
    }

    /**
     * P1-4G检卡回调
     */
    private ReadCardCallback readCardCallback = new ReadCardCallback.Stub() {

        @Override
        public void onCardDetected(CardInfo cardInfo) throws RemoteException {
            Message message = new Message();
            message.what = 0x01;
            message.obj = cardInfo;
            mHandler.sendMessage(message);
        }

        @Override
        public void onError(int i, String s) throws RemoteException {
            Message message = new Message();
            message.what = 0x02;
            message.obj = "code:" + i + " message:" + s;
            mHandler.sendMessage(message);
        }

        @Override
        public void onStartCheckCard() throws RemoteException {
        }

    };

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0x01:
                    CardInfo cardInfo = (CardInfo) msg.obj;
                    String uuid = cardInfo.uuid;
                    liveData.postValue(uuid);
                    //getUUIDMemeberData(uuid);
                    break;
                case 0x02:
                    showContent(R.string.checkCardError);
                    close();
                    break;
            }
        }

    };


    /**
     * P2刷卡
     */

    private void checkCard() {
        try {
            SunmiReadCardHelper.getInstance().getReadCardOptV2().checkCard(AidlConstantsV2.CardType.MIFARE.getValue(), mCheckCardCallback, 10);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * P2检卡回调
     */
    private CheckCardCallbackV2 mCheckCardCallback = new CheckCardCallbackV2Wrapper() {

        @Override
        public void findMagCard(Bundle bundle) throws RemoteException {

            Log.d("xxxxx","11111");
        }

        @Override
        public void findICCard(String atr) throws RemoteException {
            Log.d("xxxxx","222222");

        }

        @Override
        public void findRFCard(String uuid) throws RemoteException {
            //getUUIDMemeberData(uuid);
            Log.d("xxxxx","33333333");
            liveData.postValue(uuid);
        }

        @Override
        public void onError(int code, String message) throws RemoteException {
            Log.d("xxxxx","444444");
            checkCard();
        }
    };

    /**
     * 取消检卡 首页有刷卡功能
     */
    private void cancelCard() {
        try {
            // 终止检卡
            SunmiReadCardHelper.getInstance().getReadCardOpt().cancelCheckCard();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 取消检卡P2
     */
    private void cancelCheckCard() {
        try {
            SunmiReadCardHelper.getInstance().getReadCardOptV2().cardOff(AidlConstantsV2.CardType.MIFARE.getValue());
            SunmiReadCardHelper.getInstance().getReadCardOptV2().cancelCheckCard();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void cancelCards() {
        String versionData = ApkInfoUtil.getVersionData();
        if (!StringUtils.isEmpty(versionData)) {
            if ("P1_4G".equals(versionData)) {
                cancelCard();
            } else {
                cancelCheckCard();
            }
        }
    }

    public void showContent(int r) {
        if (activity != null)
            ToastUtils.showToast(activity, activity.getResources().getString(r));
        else if (dialogFragment != null)
            ToastUtils.showToast(dialogFragment.getContext(), dialogFragment.getContext().getResources().getString(r));
    }


    /**
     * 关闭
     */
    public void close() {
        if (activity != null)
            activity.finish();
        else if (dialogFragment != null)
            dialogFragment.dismiss();
    }

    @Override
    public void onDestroy(@NonNull LifecycleOwner owner) {
        cancelCards();
        activity = null;
        dialogFragment = null;
        mHandler.removeCallbacksAndMessages(null);
    }

}
